package com.sky.alogrithm.chapter01_data_structure;

import java.util.Stack;

/**
 * 使用双栈计算表达式的值
 */
public class Evaluate {


    public static void main(String[] args) {
        calculate("(1+2)");
    }

    public static void calculate(String strs){
        Stack<String> ops = new Stack<>();
        Stack<Double> vals = new Stack<>();
        String[] split = strs.split("");
        for(int i = 0; i < split.length; i++){
            String str = split[i];
            if(str.equals("(")){

            }else if(str.equals("+")){
                ops.push(str);
            }else if(str.equals("-")){
                ops.push(str);
            }else if(str.equals("*")){
                ops.push(str);
            }else if(str.equals("/")){
                ops.push(str);
            }else if(str.equals("sqrt")){
                ops.push(str);
            }else if(str.equals(")")){
                String op = ops.pop();
                double v = vals.pop();
                if(op.equals("+")){
                    v = vals.pop() + v;
                }else if(op.equals("-")){
                    v = vals.pop() - v;
                }else if(op.equals("*")){
                    v = vals.pop() * v;
                }else if(op.equals("/")){
                    v = vals.pop() / v;
                }else if(op.equals("sqrt")){
                    v = Math.sqrt(v);
                }
                vals.push(v);
            }else {
                vals.push(Double.parseDouble(str));
            }
        }
        System.out.println(vals.pop());
    }

}
